<template><!--积分：团队积分，个人积分-->
  <!---->
  <SearchTable
    :columns="listCol" 
    :data="IntegralData"
    :total="IntegralTotal"
    :page.sync="currentPage"
    :size.sync="compitionPZ"
    @queryFun="getCtfIntegral">
    <template slot="alert">
      <Collapse simple>
        <Panel name="1">
          手动操作
          <p slot="content">
            <Alert type="warning">
              积分计算需要满足的条件:
                <p>1、团队及团队人员配置完成</p>
              <p>2、题目分配完成</p>
              </Alert>
            <Button type="primary" ghost icon="md-add" @click="doIntegralCom" :disabled="!canCalc||disabledAllBtn"><span>重新计算积分</span></Button>
            <!--<Button type="primary" icon="ios-download-outline" @click="doOutputReport(0)">导出积分排行</Button>-->
          </p>
        </Panel>
      </Collapse>
    </template>
</SearchTable>
</template>

<script>
  import {
    integralCom,
    cancelIntegralCom,
    outputExport,
    listCtfIntegral,
    listUserCtfIntegral,
    getCtfGameboxlist
  } from '@/api/compitionStatic'
  import {integralCalc,getIntegralList} from '@/api/compitionStatic'
  import {getuserinstance} from '@/api/access_new'
  import {queryTargetAllot, queryCtfTargetAllot, getTargetTeamList, queryAllotTopoTargetList,queryAllotTopoTargetList_old} from '@/api/drill_compete'
  export default {
    name: 'integral',
    props:['type','sceneType','disabledAllBtn','hwType'],
    components:{},
    data() {
    	let title;
    	if(this.type == 0){
    		title = '团队名称'
    	}else{
    		title = '用户名称'
    	}
      return {
        IntegralData: [],
        userIntegralData: [],
        IntegralTotal: 0,
        userIntegralTotal: 0,
        scenceId: '',
        scenceName: '',
        list: [],
        formValidate: {
          matchMode: this.$route.query.matchMode
        },
        compitionPZ: 10,
        currentPage: 1,
        listCol: [{
            title: '排名',
            key: 'rank',
            align: 'center',
            placement:'top-right',
            order:2,
            render:(h,params) => {
		            	let ele;
                  let rank = params.row.rank
		            	if(rank <= 3){
		            		ele = h('img',{
		            			attrs:{
		            				src:require(`../../../../assets/scene/top${rank}.png`)
		            			},
		            			style:{
		            				display:'inline-block',
//		            				width:'20px',
		            				verticalAlign: 'text-bottom',
    										marginLeft: '20px'
		            			}
		            		})
		            	}else{
		            		ele = h('span', rank)
		            	}
		            	let index = rank;
		            	let color = 'var(--default-color)';
		            	if(this.currentPage == 1){
		            		if(index == 1){
			            		color = '#f34938';
			            	}else if(index == 2){
			            		color = '#eb8205';
			            	}else if(index == 3){
			            		color = '#27b666';
			            	}else{
			            		color = 'var(--default-color)'
			            	}
		            	}
		            	return h('span',[
		            		h('span',{
		            			style:{
		            				color:color
		            			}
		            		},'排行'),
		            		ele
		            	]);
		            }
          },
          {
            title: title,
            key: 'teamName',
            placement:'top-left',
            order:1,
              width: 240,
              tooltip:true
          },
//        {
//          title: '原始总分',
//          key: 'formerScore'
//        },
          {
            title: '有效总分',
            key: 'score',
            tooltip:true,
            width:60,
          },
          {
            title: '积分（百分制）',
            key: 'integral',
            tooltip:true,
            width:60,
          },
          {
            title: '创建时间',
            key: 'createTime'
          },
        ],
		    timeout:{},
		    canCalc:false,
      }
    },
    filters: {

    },
    beforeDestroy(){
    	 clearTimeout(this.timeout);
    },
    mounted() {
      //this.doIntegralCom();
      clearTimeout(this.timeout);
      Promise.all([this.getAllProjectGroupMember(),this.getTargetTeamList()]).then(data => {
      	if(data.every(item => item > 0)){ //有人员和靶标才允许计算积分
      		this.canCalc = true;
      	}else{
      		this.canCalc = false;
      	}
      	this.getCtfIntegral();
      })
    },
    methods: {
      integralChangeSize(page) {
        this.compitionPZ = page;
        this.getCtfIntegral();
      },
      integralOnChange(page) {
        this.currentPage = page;
        this.getCtfIntegral();
      },
      doOutputReport(contestType) {
        let _this = this;
        let params = {
          contestId: this.$route.query.id,
          contestName: this.$route.query.name,
          contestType: contestType,
          matchMode: this.formValidate.matchMode
        };
        let str = "团队积分";
        if (contestType === 1) {
          str = "个人积分";
        }
        outputExport(params).then(data => {
          console.log(data) //打印出来是blob对象，已经不是乱码了
          let url = window.URL.createObjectURL(data); //表示一个指定的file对象或Blob对象
          console.log(url, "看一下这是啥")
          let a = document.createElement("a");
          document.body.appendChild(a);
          let fileName = this.$route.query.name + str + ".xls"; //filename名称截取
          a.href = url;
          a.download = fileName; //命名下载名称
          a.click(); //点击触发下载
          window.URL.revokeObjectURL(url); //下载完成进行释放
        })
      },

      getCtfIntegral(page, pageSize) {
        let _this = this;
        let params = {};
        params.pageIndex = _this.currentPage || 1;
        params.pageSize = _this.compitionPZ || 20;
        if (this.$route.query.id) {
        	 getIntegralList(this.$route.query.id,this.type,params).then(data => {
        	 	 if(data.code == 1){
        	 	 	  this.IntegralData = data.data.items;
        	 	 	  this.IntegralTotal = data.data.total;
        	 	 	  if(this.IntegralData.length == 0){
        	 	 	  	if(this.canCalc){
        	 	 	  		this.doIntegralCom();
        	 	 	  	}
        	 	 	  }
        	 	 }
        	 })
        }
      },
      doIntegralCom() {
        let _this = this;
        integralCalc(this.$route.query.id).then(data => {
          if (data.code == 1) {
            this.$Message.info('积分计算完成！');
            clearTimeout(this.timeout);
            this.timeout = setTimeout(() => {
            	_this.getCtfIntegral();
            },3000)
          } else {
            //_this.$Message.success(data.message);
          }
        })
      },
      //查询场景人员，查询有数据即可，查询全部数据，开销太大了
      getAllProjectGroupMember(){
      	return new Promise((resolve,reject) => {
      		let params = {
						testId:this.$route.query.id,
						pageIndex:1,
						pageSize:20 
					}
					getuserinstance(params).then(data => {
						if(data.code == 1){
							let allProjectGroupMember = data.data.items.filter(item => item.inviterName != '内部服务用户');
							resolve(allProjectGroupMember.length);
						}else{
							resolve(0);
						}
					}).catch(error => {
						resolve(0);
					})
      	})
	    },
      //查询靶标分配，查询有数据即可，查询全部数据，开销太大了
      getTargetTeamList(){
    		return new Promise((resolve,reject) => {
    			if([1, 4, 8, 9].includes(this.sceneType)){
    				//攻防
                    let params = {
                        pageIndex:1,
                        pageSize:20,
                        sceneId:this.$route.query.id,
                    }
                    queryTargetAllot(params).then(data => {
			  			if(data.code==1){
			  				let targetList = data.data.items || data.data;
			  				resolve(targetList.length);
			  			}else{
			  				resolve(0);
			  			}
			  		}).catch(error => {
			  			resolve(0);
			  		})
    			}else if(this.sceneType === 0){
    				//对抗演练
                    let params = {
                        pageIndex:1,
                        pageSize:20,
                        sceneId:this.$route.query.id,
                        projectId:this.$route.query.prjid
                    }
			  		getTargetTeamList(params).then(data => {
			  			if(data.code==1){
			  				let targetList = data.data.items || data.data;
			  				resolve(targetList.length);
			  			}else{
			  				resolve(0);
			  			}
			  		}).catch(error => {
			  			resolve(0);
			  		})
    			}else if(this.sceneType == 2){
    				let params = {
                        pageIndex:1,
                        pageSize:20,
                        sceneId:this.$route.query.id,
                    }
	        	    queryCtfTargetAllot(params).then(data => {
			  			if(data.code==1){
			  				let targetList = data.data.items || data.data;
			  				resolve(targetList.length);
			  			}else{
			  				resolve(0);
			  			}
			  		}).catch(error => {
			  			resolve(0);
			  		})
                } else if (this.sceneType == 5) {
                  let queryApi = this.hwType === 0 ? queryAllotTopoTargetList_old : queryAllotTopoTargetList;
                  queryApi({
                        pageIndex:1,
                        pageSize:10,
                        projectId:this.$route.query.prjid,
                        sceneId:this.$route.query.id
                    }).then(data => {
                        if(data.code == 1){
                            resolve(data.data.total);
                        }else{
                            resolve(0);
                        }
                    }).catch(error => {
                        resolve(0);
                    })
                }
	  		})
	  	},   
    }
  }
</script>

<style>
  .tables .ivu-poptip-body {
    text-align: left !important;
  }
</style>
<style scoped>
  .Titles {
    background: #eeeeee;
    margin: 16px auto;
    padding: 10px 0;
  }

  .targetHeader {
    padding: 10px;
    margin-bottom: 10px;
  }
</style>
